package es.mllacer.qqsm;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import es.mllacer.qqsm.tasks.AddFriendTask;
import es.mllacer.qqsm.util.Utils;

public class Settings extends Activity implements LocationListener {

	private TextView userTextView = null;
	private TextView longitudeTextView = null;
	private TextView latitudeTextView = null;
	private TextView friendTextView = null;
	private ToggleButton locateButton = null;
	private TextView locationTextView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_layout);

		userTextView = (TextView) findViewById(R.id.settings_name);
		longitudeTextView = (TextView) findViewById(R.id.settings_longitude);
		latitudeTextView = (TextView) findViewById(R.id.settings_latitude);
		friendTextView = (TextView) findViewById(R.id.settings_friend);
		locateButton = (ToggleButton) findViewById(R.id.settings_button_locate);
		locationTextView = (TextView) findViewById(R.id.settings_location);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Load preferences at this point because toggle button is not loaded
		// correctly on screen orientation changed...
		loadPreferences();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// Store preferences
		storePreferences();
		// Disable automatic location
		locationDisabled();
	}

	public void locateAction(View view) {
		SharedPreferences prefs = getSettingsPreferences();
		Editor editor = prefs.edit();

		boolean enabled = prefs.getBoolean(Utils.LOCATE_PREFERENCE, true);
		if (enabled) { // disable the automatic location
			locationDisabled();
		} else { // enable the automatic location
			locationEnabled();
		}

		editor.putBoolean(Utils.LOCATE_PREFERENCE, !enabled);
		editor.commit();
	}

	// A work around for detecting the WIFI status because
	// isProviderEnabled(LocationManager.NETWORK_PROVIDER) always return true...
	private boolean wifiProviderEnabled() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo[] nwInfos = connectivity.getAllNetworkInfo();
		for (NetworkInfo nwInfo : nwInfos) {
			if (nwInfo.getTypeName() != null
					&& "wifi".equals(nwInfo.getTypeName().toLowerCase())) {
				return nwInfo.isAvailable();
			}
		}

		return true;
	}

	private void locationEnabled() {
		locateButton.setChecked(true);
		// change text button to not locate
		locateButton.setText(R.string.settings_not_locate);

		LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// If the GPS_PROVIDER is enable use it
		if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
					this);
		}
		// Otherwise, if the NETWORK_PROVIDER is enabled use it
		else if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			if (wifiProviderEnabled()) {
				manager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, 0, 0, this);
			} else {
				Toast.makeText(this, R.string.settings_enable_gps_wifi,
						Toast.LENGTH_LONG).show();
			}
		} else {
			Toast.makeText(this, R.string.settings_enable_gps_wifi,
					Toast.LENGTH_LONG).show();
		}
	}

	private void locationDisabled() {
		locateButton.setChecked(false);
		// change text button to locate me
		locateButton.setText(R.string.settings_locate);

		// remove the automatic updates
		((LocationManager) getSystemService(Context.LOCATION_SERVICE))
				.removeUpdates(this);
	}

	public void addFriendAction(View view) {
		AsyncTask<Void, Integer, Boolean> task = new AddFriendTask(this);
		task.execute();
	}

	private SharedPreferences sharedPreferences = null;

	public SharedPreferences getSettingsPreferences() {
		if (sharedPreferences == null) {
			sharedPreferences = getSharedPreferences(
					Utils.SETTINGS_PREFERENCES, MODE_PRIVATE);
		}
		return sharedPreferences;
	}

	protected void loadPreferences() {
		SharedPreferences prefs = getSettingsPreferences();

		// Load preferences
		userTextView.setText(prefs.getString(Utils.USER_PREFERENCE, ""));
		longitudeTextView.setText(String.valueOf(prefs.getFloat(
				Utils.LONGITUDE_PREFERENCE, 0)));
		latitudeTextView.setText(String.valueOf(prefs.getFloat(
				Utils.LATITUDE_PREFERENCE, 0)));
		friendTextView.setText(prefs.getString(Utils.FRIEND_PREFERENCE, ""));
		locationTextView
				.setText(prefs.getString(Utils.LOCATION_PREFERENCE, ""));

		boolean enabled = prefs.getBoolean(Utils.LOCATE_PREFERENCE, false);
		if (enabled) { // automatic location enabled
			locationEnabled();
		} else { // automatic location disabled
			locationDisabled();
		}
	}

	protected void storePreferences() {
		SharedPreferences prefs = getSettingsPreferences();
		Editor editor = prefs.edit();

		editor.putString(Utils.USER_PREFERENCE, userTextView.getText()
				.toString());
		editor.putFloat(Utils.LONGITUDE_PREFERENCE,
				Float.parseFloat(longitudeTextView.getText().toString()));
		editor.putFloat(Utils.LATITUDE_PREFERENCE,
				Float.parseFloat(latitudeTextView.getText().toString()));
		editor.putString(Utils.LOCATION_PREFERENCE, locationTextView.getText()
				.toString());

		editor.commit();
	}

	@Override
	public void onLocationChanged(Location location) {
		if (location == null) {
			return;
		}

		double latitude = location.getLatitude();
		double longitude = location.getLongitude();

		// Update settings location
		longitudeTextView.setText(String.valueOf(longitude));
		latitudeTextView.setText(String.valueOf(latitude));
		locationTextView.setVisibility(TextView.VISIBLE);
		locationTextView.setText(Utils.getAddress(this, latitude, longitude));
	}

	@Override
	public void onProviderEnabled(String provider) {
		if (provider.equals(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, R.string.settings_gps_enabled,
					Toast.LENGTH_LONG).show();
		} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
			Toast.makeText(this, R.string.settings_wifi_enabled,
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		if (provider.equals(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, R.string.settings_gps_disabled,
					Toast.LENGTH_LONG).show();
		} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
			Toast.makeText(this, R.string.settings_wifi_disabled,
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

}
